package com.w3coffee.web.control;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import com.w3coffee.web.Branch;

public class VerifyLocationController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public ModelAndView handleRequest(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> model = getDefaultModel(req);
		HttpSession session = req.getSession();
		CheckinToken ct = (CheckinToken) session.getAttribute("TOKEN");
		
		double lng, lat, acy;
		try {
			lng = Double.parseDouble(req.getParameter("lng"));
			lat = Double.parseDouble(req.getParameter("lat"));
			acy = Double.parseDouble(req.getParameter("acy"));
		} catch (Exception e) {
			logger.error("Get GPS location parameter fail.", e);
			return adaptive(req, resp, "welcome", model);
		}
		
		Branch branch = ContextServlet.getBranch(lng, lat, acy);
		if (branch == null) {
			return adaptive(req, resp, "toofar", getDefaultModel(req));
		} else {
			ct.setBranch(branch);
			ct.setCheckinTime(new Date().getTime());
		}
		
		String backUrl = (String) session.getAttribute("backUrl");
		if (backUrl != null) {
			resp.sendRedirect(backUrl);
			return null;
		} else {
			return adaptive(req, resp, "welcome", model);
		}
	}

}
